package org.jeecg.modules.online.cgform.util;

import cn.hutool.core.util.ReUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.cgform.entity.OnlCgformButton;
import org.jeecg.modules.online.cgform.entity.OnlCgformEnhanceJs;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.enums.CgformConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * js 增强工具类
 */
@Slf4j
public class EnhanceJsUtil {

    private static final String enhanceJsButtonCode = "beforeAdd,beforeEdit,afterAdd,afterEdit,beforeDelete,afterDelete,mounted,created,show";

    /**
     * 第二个方法 前面是}，需要替换成},
     */
    private static final String second_fun_pre = "\\}\\s*\r*\n*\\s*";

    private static final String comma = ",";


    public static void main(String[] args) {
        String js = "aa(row){console.log(112);}\n" +
                "bb(row){console.log(row);}";
        String buttoncode = "bb";
        System.out.println(repalceLinkButtonJs(js,buttoncode));


        List<OnlCgformButton> cgButtonList = new ArrayList<OnlCgformButton>();
        OnlCgformButton b  = new OnlCgformButton();
        b.setButtonCode("bb");
        b.setButtonStyle("link");
        cgButtonList.add(b);

       OnlCgformButton a = new OnlCgformButton();
        a.setButtonCode("aa");
        a.setButtonStyle("link");
        cgButtonList.add(a);

        System.out.println(overFinalWriteJs(js,cgButtonList));


    }

    /**
     * 操作列上的按钮
     * 将buttonCode(){ 替换成 buttonCode:function(){
     * 或者是
     * 将buttonCode(row){ 替换成 buttonCode:function(row){
     * @param enhanceJs
     * @param buttonCode
     * @return
     */
    public static String repalceLinkButtonJs(String enhanceJs,String buttonCode){
        String patternStr = "("+buttonCode+"\\s*\\(row\\)\\s*\\{)";
        String replaceStr = buttonCode+":function(that,row){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;";
        String temp = replaceJSByPatternCanNull(enhanceJs,second_fun_pre+patternStr,"},"+replaceStr);
        if(temp==null){
            enhanceJs = replaceJSByPattern(enhanceJs,patternStr,replaceStr);
        }else{
            enhanceJs = temp;
        }
        enhanceJs = repalceCommonButtonJs(enhanceJs,buttonCode,null);
        return enhanceJs;
    }

    /**
     * 列表上方按钮 表单按钮
     *
     * @param enhanceJs
     * @param buttonCode
     * @return
     */
    public static String repalceCommonButtonJs(String enhanceJs,String buttonCode,String prefixPattern){
        String patternStr = "("+ oConvertUtils.getString(prefixPattern) +buttonCode+"\\s*\\(\\)\\s*\\{)";
        String replaceStr = buttonCode+":function(that){const getAction=this._getAction,postAction=this._postAction,deleteAction=this._deleteAction;";
        String temp = replaceJSByPatternCanNull(enhanceJs,second_fun_pre+patternStr,"},"+replaceStr);
        if(temp==null){
            enhanceJs = replaceJSByPattern(enhanceJs,patternStr,replaceStr);
        }else{
            enhanceJs = temp;
        }
        return enhanceJs;
    }

    /**
     * 根据Pattern替换字符串
     * @param enhanceJs
     * @param patternStr
     * @param replaceStr
     * @return
     */
    public static String replaceJSByPatternCanNull(String enhanceJs,String patternStr,String replaceStr){
        Pattern p = Pattern.compile(patternStr);
        Matcher m = p.matcher(enhanceJs);
        if(m.find()) {
            enhanceJs = enhanceJs.replace(m.group(0), replaceStr);
            return enhanceJs;
        }else{
            return null;
        }
    }

    public static String replaceJSByPattern(String enhanceJs,String patternStr,String replaceStr){
        String temp = replaceJSByPatternCanNull(enhanceJs,patternStr,replaceStr);
        if(temp != null){
            return temp;
        }
        return enhanceJs;
    }



    public static String getFormEnhanceJs(String enhanceJs,List<OnlCgformButton> cgButtonList) {
        log.info("最终的增强JS",enhanceJs);
        return "class OnlineEnhanceJs{constructor(getAction,postAction,deleteAction){this._getAction=getAction;this._postAction=postAction;this._deleteAction=deleteAction;}"+enhanceJs+"}";
    }


    /**
     * 字段change事件
     * @param enhanceJs
     * @param fieldName
     * @return
     */
    public static String repalceFieldChangeJs(String enhanceJs,String fieldName){
        String patternStr = "(\\s+"+fieldName+"\\s*\\(\\)\\s*\\{)";
        String replaceStr = fieldName+":function(that,event){";
        String temp = replaceJSByPatternCanNull(enhanceJs,second_fun_pre+patternStr,"},"+replaceStr);
        if(temp==null){
            enhanceJs = replaceJSByPattern(enhanceJs,patternStr,replaceStr);
        }else{
            enhanceJs = temp;
        }
        return enhanceJs;
    }

    public static String theLastString(String enhanceJs){
        String theLastString = "function OnlineEnhanceJs(getAction,postAction,deleteAction){return {_getAction:getAction,_postAction:postAction,_deleteAction:deleteAction,"+enhanceJs+"}}";
        log.info("最终的增强JS",theLastString);
        return theLastString;
    }

    /**
     * 列表/表单 页面的js增强格式化方法
     * @param enhanceJs
     * @param cgButtonList
     * @return
     */
    public static String overFinalWriteJs(String enhanceJs, List<OnlCgformButton> cgButtonList) {
        enhanceJs = overwriteClearButton(enhanceJs,cgButtonList);
        String theLastString = "function OnlineEnhanceJs(getAction,postAction,deleteAction){return {_getAction:getAction,_postAction:postAction,_deleteAction:deleteAction,"+enhanceJs+"}}";
        log.info("最终的增强JS",theLastString);
        return theLastString;
    }

    public static String overwriteClearButton(String enhanceJs, List<OnlCgformButton> cgButtonList){
        if(cgButtonList!=null) {
            for (OnlCgformButton button : cgButtonList) {
                String buttonCode = button.getButtonCode();
                if("link".equals(button.getButtonStyle())) {
                    enhanceJs = repalceLinkButtonJs(enhanceJs,buttonCode);
                }else if("button".equals(button.getButtonStyle()) || "form".equals(button.getButtonStyle())) {
                    enhanceJs = repalceCommonButtonJs(enhanceJs,buttonCode,null);
                }
            }
        }
        for (String temp : enhanceJsButtonCode.split(",")) {
            if("beforeAdd,afterAdd,mounted,created,show".indexOf(temp)>=0) {
                enhanceJs = repalceCommonButtonJs(enhanceJs,temp,null);
            }else {
                enhanceJs = repalceLinkButtonJs(enhanceJs,temp);
            }
        }
        return enhanceJs;
    }

    /**
     * 单表或主表，JS增强生成
     * change方法命名： onlChange
     */
    public static void overwriteJsOneOrMain(OnlCgformEnhanceJs onlCgformEnhanceJs,String tbname, List<OnlCgformField> fieldList) {
        if(onlCgformEnhanceJs==null || oConvertUtils.isEmpty(onlCgformEnhanceJs.getCgJs())) {
            return;
        }
        //先加个空格，防止正则匹配不到这种情况 =>（js增强直接以onlChange开头对齐）
        String enhanceJs = " " + onlCgformEnhanceJs.getCgJs();
        log.info("one enhanceJs begin==> "+enhanceJs);
        //处理主表onlChange方法【change方法命名： onlChange】
        Pattern p = Pattern.compile("(\\s{1}"+CgformConstant.ONLINE_JS_CHANGE_FUNCTION_NAME+"\\s*\\(\\)\\s*\\{)");
        Matcher m = p.matcher(enhanceJs);
        if(m.find()) {
            log.info("---JS 增强转换-main--enhanceJsFunctionName----"+ CgformConstant.ONLINE_JS_CHANGE_FUNCTION_NAME);
            enhanceJs = repalceCommonButtonJs(enhanceJs,CgformConstant.ONLINE_JS_CHANGE_FUNCTION_NAME,"\\s{1}");
            for (OnlCgformField field : fieldList) {
                //TODO 主表和子表有，重名的字段会出问题
                enhanceJs = repalceFieldChangeJs(enhanceJs,field.getDbFieldName());
            }
        }
        log.info("one enhanceJs end==> "+enhanceJs);
        onlCgformEnhanceJs.setCgJs(enhanceJs);
    }

    /**
    * 子表，JS增强生成
    * change方法命名： {子表名}_onlChange
    */
    public static void overwriteJsSub(OnlCgformEnhanceJs onlCgformEnhanceJs, String tbname, List<OnlCgformField> fieldList) {
        if(onlCgformEnhanceJs==null || oConvertUtils.isEmpty(onlCgformEnhanceJs.getCgJs())) {
            return;
        }
        log.info(" sub enhanceJs begin==> "+onlCgformEnhanceJs);
        String enhanceJs = onlCgformEnhanceJs.getCgJs();
        //子表 change JS方法名字
        String enhanceJsFunctionName = tbname + "_" + CgformConstant.ONLINE_JS_CHANGE_FUNCTION_NAME;

        //转换子表主change方法和字段方法
        //TODO 子表表名命名，有包含匹配的会有问题
        Pattern p = Pattern.compile("("+ enhanceJsFunctionName +"\\s*\\(\\)\\s*\\{)");

        Matcher m = p.matcher(enhanceJs);
        if(m.find()) {
            log.info("---JS 增强转换-sub-- enhanceJsFunctionName----"+ enhanceJsFunctionName);
            enhanceJs = repalceCommonButtonJs(enhanceJs,enhanceJsFunctionName,null);
            for (OnlCgformField field : fieldList) {
                //TODO  主表和子表有，重名的字段会出问题
                enhanceJs = repalceFieldChangeJs(enhanceJs,field.getDbFieldName());
            }
        }
        log.info(" sub enhanceJs end==> "+enhanceJs);
        onlCgformEnhanceJs.setCgJs(enhanceJs);
    }
}
